package com.netease.examination.web;

import com.netease.examination.dto.ResultDTO;
import com.netease.examination.service.LoginService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * designed by destiny
 *
 * @author destiny
 *         e-mail destinywk@163.com
 *         github https://github.com/DestinyWang
 *         oschina https://git.oschina.net/destinywk
 * @version JDK 1.8.0_101
 * @since 2017/3/30 22:16
 */
@Controller
public class LoginController {

    @Resource
    private LoginService loginService;

    /**
     * 用户登录
     * 验证登录的同时生成token并下发
     * 使用【用户名】+【密码】+【时间戳】+【盐值】进行MD5加密
     * 同时在session和cookie中生成
     *
     * @param userName
     * @param password
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST})
    @CrossOrigin
    @ResponseBody
    public ResultDTO userLogin(@RequestParam("userName") String userName,
                               @RequestParam("password") String password,
                               HttpServletRequest request,
                               HttpServletResponse response) {

        String passConfirm = loginService.findPassword(userName);
        Boolean passwordCorrect = passConfirm != null && passConfirm.equals(password);
        Integer identity = userName.equals("buyer") ? 0 : 1;

        if (passwordCorrect) {
            String tokenStr = loginService.getToken(userName, password);
            Cookie token = new Cookie("token", tokenStr);
            token.setMaxAge(2 * 60 * 60);
            token.setPath("/");
            response.addCookie(token);

            HttpSession session = request.getSession();
            session.setAttribute("token", tokenStr);
            session.setMaxInactiveInterval(15 * 60);
        }

        return new ResultDTO<Integer>(passwordCorrect, identity);
    }

    @RequestMapping(value = "/logout", method = {RequestMethod.POST, RequestMethod.GET})
    @CrossOrigin
    @ResponseBody
    public ResultDTO logout(@CookieValue("token") String ticket,
                            HttpServletRequest request,
                            HttpServletResponse response) {
        HttpSession session = request.getSession();
        session.setAttribute("token", null);

        for (Cookie cookie : request.getCookies()) {
            if ("token".equals(cookie.getName())) {
                cookie.setValue(null);
            }
        }

        return new ResultDTO(true, null);
    }

}
